'use strict';

const Controller = require('egg').Controller;

class GroupController extends Controller {
    //获取
    async getGroup() {
        const { ctx } = this;
        const data = await this.app.mysql.select('groups');
        data.forEach((item, index) => {
            item.key = index + 1;
        })
        ctx.body = {
            code: 200,
            data,
        };
    }

    //搜索
    async searchGroup() {
        const { ctx } = this;
        const { name, state, province, city, county, word } = ctx.query;
        const data = await this.app.mysql.query(`SELECT * FROM groups WHERE name Like "%${name}%" 
        and state Like "%${state}%"
        and city Like "%${city}%"
        and province Like "%${province}%"
        and county Like "%${county}%"
        and word Like "%${word}%"`);
        data.forEach((item, index) => {
            item.key = index + 1;
        })
        ctx.body = {
            code: 200,
            data,
        };
    }

    //删除
    async deleteGroup() {
        const { ctx } = this;
        const { id } = ctx.query;
        const data = await this.app.mysql.delete('groups', {
            id: id,
        });
        if (data.affectedRows !== 1) {
            ctx.body = {
                code: 500,
                message: "删除失败"
            };
        }
        ctx.body = {
            code: 200,
            message: "删除成功"
        };
    }

    //开关的编辑
    async stateGroup() {
        const { ctx } = this;
        const { id } = ctx.request.body;
        let list = await this.app.mysql.get('groups', { id: id });
        list.state = !list.state;
        const data = await this.app.mysql.update('groups', {
            ...list
        });
        if (data.affectedRows !== 1) {
            ctx.body = {
                code: 500,
                message: "修改失败"
            };
        }
        ctx.body = {
            code: 200,
            message: "修改成功"
        };
    }
}

module.exports = GroupController;
